package com.uniknow.app.ui;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;

import com.tencent.connect.UserInfo;
import com.tencent.connect.auth.QQAuth;
import com.tencent.tauth.IUiListener;
import com.tencent.tauth.Tencent;
import com.uniknow.app.AppConfig;
import com.uniknow.app.AppContext;
import com.uniknow.app.R;
import com.uniknow.app.oauth.qq.BaseUiListener;
import com.uniknow.app.oauth.qq.Constants;

public class TencentActivity extends BaseActivity {
	private AppContext appContext;
	private Tencent mTencent;
	public static QQAuth mQQAuth;
	private UserInfo mInfo;
	
	private Intent resultIntent;
	
	private ImageView mUserLogo;
	private Button mNewLoginButton;
	private TextView mBaseMessageText;
	private TextView mMessageText;
	
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_tencent);
		
		appContext = (AppContext) this.getApplicationContext();
		
		//mQQAuth = null;
		resultIntent = new Intent();
		mQQAuth = QQAuth.createInstance(Constants.APP_ID, AppContext.getInstance());
		mTencent = Tencent.createInstance(Constants.APP_ID, TencentActivity.this);
		initViews();
		
	}
	
	private void initViews(){
		mBaseMessageText = (TextView) findViewById(R.id.BaseMessageText);
		mUserLogo = (ImageView) findViewById(R.id.user_logo);
		mMessageText = (TextView) findViewById(R.id.MessageText);
		mNewLoginButton = (Button) findViewById(R.id.newloginbtn);
		
		mNewLoginButton.setOnClickListener(new OnClickListener() {
			
			@Override
			public void onClick(View arg0) {
				// TODO Auto-generated method stub
				onClickLogin(false);
			}
		});
		onClickLogin(true);
		//updateLoginButton();
	}	
	
	private void updateLoginButton() {
		if (mQQAuth != null&&mQQAuth.isSessionValid()) {
			mNewLoginButton.setTextColor(Color.RED);
			mNewLoginButton.setText("退出帐号");
			resultIntent.putExtra("login_statu", true);
			resultIntent.putExtra("user_name", AppConfig.QQAuthUserName);
		} else {
			resultIntent.putExtra("login_statu", false);
			mNewLoginButton.setTextColor(Color.BLUE);
			mNewLoginButton.setText("登录");
		}
	}
	
	private void updateUserInfo() {
		if (mQQAuth != null && mQQAuth.isSessionValid()) {
			IUiListener listener = new BaseUiListener(TencentActivity.this) {
				@Override
				protected void doComplete(JSONObject response) {
					JSONObject json = (JSONObject)response;
					System.out.println("json = "+json.toString());
					try{
						if(json.has("figureurl_qq_2")){
							//bmpManager.loadBitmap(json.getString("figureurl_qq_2"),mUserLogo, null);
							AppConfig.QQAuthUserPhotoURL = json.getString("figureurl_qq_2");
							mUserLogo.setVisibility(android.view.View.VISIBLE);
						}
						if (json.has("nickname")) {
							mMessageText.setVisibility(android.view.View.VISIBLE);
							mMessageText.setText(json.getString("nickname"));
							AppConfig.QQAuthUserName = json.getString("nickname");
							resultIntent.putExtra("login_statu", true);
							resultIntent.putExtra("user_name", json.getString("nickname"));
						}
						/**保存用户QQAuthInfo到配置表*/
						//写入SharedPreferences
						SharedPreferences preferences = TencentActivity.this.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
						Editor editor = preferences.edit();
						// 存入数据					
						editor.putString("QQAuthUserName", AppConfig.QQAuthUserName);
						editor.putString("QQAuthUserPhotoURL", AppConfig.QQAuthUserPhotoURL);
						// 提交修改
						editor.commit();
						/***************************/
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
			};

//			mTencent.requestAsync(Constants.GRAPH_SIMPLE_USER_INFO, null,Constants.HTTP_GET, requestListener, null);
			mInfo = new UserInfo(this, mQQAuth.getQQToken());
			mInfo.getUserInfo(listener);
			
		} else {
			mMessageText.setText("登录");
			mMessageText.setVisibility(android.view.View.GONE);
			mMessageText.setVisibility(android.view.View.GONE);
		}
	}
	
	
	private void onClickLogin(boolean isOEM) {
		System.out.println("mNewLoginButton = "+mNewLoginButton.getText().toString()+" size = "+mNewLoginButton.getText().toString().length());
		if (!mQQAuth.isSessionValid()&&mNewLoginButton.getText().toString().length()<3) {
			System.out.println("登录操作  isOEM = "+isOEM);
			IUiListener listenerLogin = new BaseUiListener(TencentActivity.this) {
				@Override
				protected void doComplete(JSONObject values) {
					JSONObject json = (JSONObject)values;
					try {
						if(json.has("openid")){
							AppConfig.TencentOpenId = json.getString("openid");
						}
						if(json.has("expires_in")){
							AppConfig.TencentExpiresIn = json.getString("expires_in");					
						}
						if(json.has("access_token")){
							AppConfig.TencentAccessToken = json.getString("access_token");
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
					//写入SharedPreferences
					SharedPreferences preferences = TencentActivity.this.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
					Editor editor = preferences.edit();
					// 存入数据					
					editor.putString("TencentOpenId", AppConfig.TencentOpenId);
					editor.putString("TencentExpiresIn", AppConfig.TencentExpiresIn);
					editor.putString("TencentAccessToken", AppConfig.TencentAccessToken);
					// 提交修改
					editor.commit();
					updateUserInfo();
					updateLoginButton();
				}
			};
			if(isOEM){
				System.out.println("isOEM");
				mTencent.setOpenId(AppConfig.TencentOpenId);
				mTencent.setAccessToken(AppConfig.TencentAccessToken, AppConfig.TencentExpiresIn);
				mTencent.login(this, "all", listenerLogin);
				//mTencent.loginWithOEM(this, "all", listenerLogin,AppConfig.TencentOpenId,AppConfig.TencentExpiresIn,AppConfig.TencentAccessToken);
			}else{
				mQQAuth.login(this, "all", listenerLogin);
			}
		} else {
			//写入SharedPreferences
			SharedPreferences preferences = TencentActivity.this.getSharedPreferences(AppConfig.SHAREDPREFERENCES_NAME, Context.MODE_PRIVATE);
			Editor editor = preferences.edit();
			// 存入数据
			editor.putString("TencentOpenId", "");
			editor.putString("TencentExpiresIn", "0");
			editor.putString("TencentAccessToken", "");
			// 提交修改
			editor.commit();
			mQQAuth.logout(this);
			updateUserInfo();
			updateLoginButton();
		}
	}
	@Override
	public void finish() {
		TencentActivity.this.setResult(100, resultIntent);
		super.finish();
	}

}
